package com.itheima.pinda.authority.controller.auth;

import com.itheima.pinda.authority.biz.service.auth.ValidateCodeService;
import com.itheima.pinda.authority.biz.service.auth.impl.AuthManager;
import com.itheima.pinda.authority.dto.auth.LoginDTO;
import com.itheima.pinda.authority.dto.auth.LoginParamDTO;
import com.itheima.pinda.base.BaseController;
import com.itheima.pinda.base.R;
import com.itheima.pinda.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:
 * @author: admin
 * @time: 2022/10/17 10:35
 */
@RestController
@RequestMapping("/anno")
@Api(tags = "登录控制器", value = "LoginController")
public class LoginController extends BaseController {

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private AuthManager authManager;
    /**
     * 前端验证码生成接口
     * @param key
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/captcha", produces = "image/png")
    @ApiOperation(notes = "验证码" ,value = "验证码")
    @SysLog("生成验证码")
    public void captcha(@RequestParam(value = "key") String key, HttpServletResponse response) throws IOException {
        validateCodeService.create(key,response);
    }


    @PostMapping("/login")
    @ApiOperation(notes = "登录" ,value = "登录")
    @SysLog("登录")
    public R<LoginDTO> login(@Validated @RequestBody LoginParamDTO loginParamDTO){
        boolean check = validateCodeService.check(loginParamDTO.getKey(), loginParamDTO.getCode());
        if (check) {

            R<LoginDTO> r = authManager.login(loginParamDTO.getAccount(),
                    loginParamDTO.getPassword());
            return r;
            //1.校验账号密码
            //2.生成jwt令牌
            //   3.将用户权限给前端使用，进行缓存
            //  4.将用户对应的权限给后端网关，进行缓存
            //  5.封装返回结果
        }
        return this.success(null);
    }

    @PostMapping("/check")
    @ApiOperation(notes = "验证码校验" ,value = "验证码校验")
    public Boolean check(@RequestBody LoginParamDTO loginParamDTO){
        return validateCodeService.check(loginParamDTO.getKey(), loginParamDTO.getCode());
    }

}
